package com.sc.ktapplication.common.util.versionmanager

import android.app.Activity
import android.app.ProgressDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import com.sc.ktapplication.BuildConfig
import com.sc.ktapplication.common.net.RetrofitManager
import com.sc.ktapplication.common.net.WebApi
import com.sc.ktapplication.common.net.okdown.FileCallBack
import com.sc.ktapplication.common.net.okdown.OkDownloader
import com.sc.ktapplication.common.util.MediaUtil
import com.sc.ktapplication.common.util.PackageUtils.getVersionCode
import com.sc.ktapplication.common.util.ToastUtil.showShort
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

/**
 * 版本升级工具
 */
object VersionUtils {

    private var webApi: WebApi = RetrofitManager.instance.create(WebApi::class.java)

    fun getUpdataInfo(context: Context, isShowToast: Boolean) {
        val body = hashMapOf<String, String>()
        body["appid"] = BuildConfig.APPLICATION_ID

        val params = hashMapOf<String,Any>()
        params["msgType"] = "sd_pw_appverion"
        params["msgBody"] = params
        try {
            GlobalScope.launch {
                val ret = webApi.checkUpdate(params)
                if(ret.isSuccess){
                   if(null != ret.data && getVersionCode(context) < ret.data.version.toInt()){
                       showDownloadDialog(context,  ret.data)
                   } else {
                       if (isShowToast) {
                           showShort( "已经是最新版本！")
                       }
                   }
                }
            }
        }catch (e : java.lang.Exception){
            e.printStackTrace()
        }
    }

    /**
     * 提示下载dialog
     */
    private fun showDownloadDialog(context: Context, updateInfo: UpdateInfo) {
        val dialog = AlertDialog.Builder(context)
        dialog.setCancelable(false)
        dialog.setTitle("升级提示")
        dialog.setMessage(updateInfo.description)
        dialog.setNegativeButton("立刻升级") { dialog1: DialogInterface, which: Int -> dialog1.dismiss()
            download(context, updateInfo)
        }
        if (updateInfo.forcedUpdate == "0") {
            dialog.setPositiveButton("以后再说") { dialog12: DialogInterface, which: Int -> dialog12.dismiss() }
        }
        dialog.create()
        dialog.show()
    }

    /**
     * 下载文件
     */
    fun download(context: Context, version: UpdateInfo) {
        val apkName = "kt.apk"
        val destDir: String = MediaUtil.getAppFolder(context)
        deleteApk(destDir + apkName)
        val pd = ProgressDialog(context)
        pd.setCancelable(false)
        pd.setMessage("正在下载，请稍后...")
        pd.progress = 0
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
        pd.show()

        OkDownloader.getInstance().url(version.address).execute(object : FileCallBack(destDir,apkName){
            override fun onResponse(file: File?, id: Int) {
                setUp(file!!.absolutePath, context)
            }

            override fun onError(call: Call?, e: java.lang.Exception?, id: Int) {

            }

            override fun inProgress(progress: Float, total: Long, id: Int) {
                pd.progress = (100 * progress).toInt()
            }

        })
    }


    private fun deleteApk(filePath: String) {
        val file = File(filePath)
        if (file.exists()) file.delete()
    }

    /**
     * 安装新版本
     */
    private fun setUp(filePath: String, context: Context) {
        val apkfile = File(filePath)
        val intent = Intent(Intent.ACTION_VIEW)
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            try {
                val ss = BuildConfig.APPLICATION_ID+".fileProvider"
                val contentUri = FileProvider.getUriForFile(context.applicationContext, ss, apkfile)
                intent.action = Intent.ACTION_VIEW
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        try {
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        /*  Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
        ((Activity) context).finish();*/
    }
}